package com.ophiux.controller;

import java.io.File;
import java.io.IOException;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.ophiux.util.DateUtil;


public class CommonService{
	private static Logger logger = LoggerFactory.getLogger(CommonService.class);
	
	public String getPicturePath(MultipartFile[] files,HttpServletRequest request) throws IOException {
		String imgPath = "";//存入数据库图片路径
		try {
			for (MultipartFile file : files) {
				if(!"image/jpeg".equals(file.getContentType())&&!"image/png".equals(file.getContentType())) {
					continue;
				}
				
				String date = DateUtil.getCurrentDate("yyyyMMdd");//图片正式路径
				
				synchronized (file) {
					String date1 = date+"_yuanjian";//图片原件
					String fileName = DateUtil.getCurrentDate("yyyyMMddHHmmss")+new Random().nextInt(1000);
					
					String oldFilePath = "/upload/"+date1+"/"+fileName+".png";
					String newFilePath = "/upload/"+date+"/"+fileName+".webp";
					File f = new File(oldFilePath);
					if(!f.exists() && !f.isDirectory()) {
						f.mkdirs();
					}
					// 转存文件  
					file.transferTo(new File(oldFilePath));
					ImageFormatConverter.convertToWebp(oldFilePath, newFilePath);
					String newPath = date+"/"+fileName+".webp,";
					imgPath=imgPath+newPath;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("上传图片异常");
			throw new IOException();
		}  
		return imgPath;
	}
}
